﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Kingdee.BOS;
using Kingdee.BOS.Util;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Core.Metadata.StateTracker;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.Metadata;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Core.Const;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.BarElement;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args.UnitTest;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;

namespace Sincetech.K3.SCM.Common
{
    /// <summary>
    /// 出库单据：单据插件(更新扩展计量单位对应数量的库存)
    /// 库存更新规则：基本单位数量、长度、支数、双数(不考虑双数明细)中只要存在一个值更新后的库存数量小于0，都不允许更新
    /// </summary>
    public class OutStock_Bill : AbstractBillPlugIn
    {
        #region 单据保存后事件
        /// <summary>
        /// 保存后事件
        /// </summary>
        /// <param name="e"></param>
        public override void AfterSave(Kingdee.BOS.Core.Bill.PlugIn.Args.AfterSaveEventArgs e)
        {
            base.AfterSave(e);

            //单据保存后，更新扩展计量的库存
        }
        #endregion

        #region 单据保存前事件
        /// <summary>
        /// 保存前事件
        /// </summary>
        /// <param name="e"></param>
        public override void BeforeSave(Kingdee.BOS.Core.Bill.PlugIn.Args.BeforeSaveEventArgs e)
        {
            base.BeforeSave(e);

            //单据保存前，判断双数明细的总数量是否与对应对应的主单据体的双数一致(避免双数明细录入后，手工修改父单据体的双数)
            /*
             * ********* 代码实现区 ***************
             */

            //在单据保存前，创建临时表(中间表)，将从数据库后台读取当前单据的相关数量到中间表中
            /*
             * ********* 代码实现区 ***************
             */
        }
        #endregion

        public override void DataChanged(DataChangedEventArgs e)
        {
            //base.DataChanged(e);
            string str_Text;
            // 获取F_ST_TEXT的值，当F_ST_TEXT的值发生变化时
            //DynamicObject f_st_text = this.View.Model.GetValue("F_st_Text") as DynamicObject;
            if (this.View.Model.GetValue("F_st_Text") != null)
            {
                str_Text = this.View.Model.GetValue("F_st_Text").ToString();
            }
            else
            {
                str_Text = "";
            }
            //并且判断F_ST_TEXT值为QueryStockUpdate时
            if (e.Field.Key.ToUpper().ToString() == "F_ST_TEXT")
            {
                string strSql;
                DataTable dt;
                //获取库存组织FSTOCKORGID
                DynamicObject FSTOCKORG = this.Model.GetValue("FSTOCKORGID") as DynamicObject;
                SubEntryEntity subEntity = this.View.BusinessInfo.GetEntity("FSubEntity") as SubEntryEntity;
                EntryEntity Entity = subEntity.ParentEntity;
                DynamicObjectCollection entryRows = this.View.Model.GetEntityDataObject(Entity);
                for (int i = 0; i < entryRows.Count; i++)
                {
                    DynamicObject currRow = entryRows[i];
                    string strOwnerType, strKeeperType, strOwner, strKeeper, strAuxProp, strMaterial, strFSTOCKORG, strLot, strLot_Text, strStockStatus, strStock, strExpiryDate, strProduceDate;
                    if (FSTOCKORG == null)
                    {
                        strFSTOCKORG = "";
                    }
                    else
                    {
                        strFSTOCKORG = FSTOCKORG["Id"].ToString();
                    }

                    if (currRow["OwnerTypeID"] == null)
                    {
                        strOwnerType = "";
                    }
                    else
                    {
                        strOwnerType = currRow["OwnerTypeID"].ToString();
                    }

                    if (currRow["KeeperTypeID"] == null)
                    {
                        strKeeperType = "";
                    }
                    else
                    {
                        strKeeperType = currRow["KeeperTypeID"].ToString();
                    }
                    DynamicObject Owner = currRow["OwnerID"] as DynamicObject;
                    if (Owner == null)
                    {
                        strOwner = "";
                    }
                    else
                    {
                        strOwner = Owner["Id"].ToString();
                    }
                    DynamicObject Keeper = currRow["KeeperID"] as DynamicObject;
                    if (Keeper == null)
                    {
                        strKeeper = "";
                    }
                    else
                    {
                        strKeeper = Keeper["Id"].ToString();
                    }
                    DynamicObject Stock = currRow["StockID"] as DynamicObject;
                    if (Stock == null)
                    {
                        strStock = "";
                    }
                    else
                    {
                        strStock = Stock["Id"].ToString();
                    }
                    DynamicObject AuxProp = currRow["AuxPropId"] as DynamicObject;
                    if (AuxProp == null)
                    {
                        strAuxProp = "";
                    }
                    else
                    {
                        strAuxProp = AuxProp["Id"].ToString();
                    }
                    DynamicObject StockStatus = currRow["StockStatusID"] as DynamicObject;
                    if (StockStatus == null)
                    {
                        strStockStatus = "";
                    }
                    else
                    {
                        strStockStatus = StockStatus["Id"].ToString();
                    }
                    DynamicObject Lot = currRow["Lot_Id"] as DynamicObject;
                    if (Lot == null)
                    {
                        strLot = "";
                    }
                    else
                    {
                        strLot = Lot.ToString();
                    }

                    if (currRow["Lot_Text"] == null)
                    {
                        strLot_Text = "";
                    }
                    else
                    {
                        strLot_Text = currRow["Lot_Text"].ToString();
                    }

                    DynamicObject Material = currRow["MaterialID"] as DynamicObject;
                    if (Material == null)
                    {
                        strMaterial = "";
                    }
                    else
                    {
                        strMaterial = Material["Id"].ToString();
                    }
                    DynamicObject ProduceDate = currRow["ProduceDate"] as DynamicObject;
                    if (ProduceDate == null)
                    {
                        strProduceDate = " t1.FPRODUCEDATE is null ";
                    }
                    else
                    {
                        strProduceDate = " t1.FPRODUCEDATE= '" + ProduceDate["Id"] + "' ";
                    }
                    DynamicObject ExpiryDate = currRow["ExpiryDate"] as DynamicObject;
                    if (ExpiryDate == null)
                    {
                        strExpiryDate = " t1.FEXPIRYDATE is null ";
                    }
                    else
                    {
                        strExpiryDate = " t1.FEXPIRYDATE= '" + ExpiryDate["Id"] + "' ";
                    }
                    //如果批号为空，通过批号查询批次
                    if (strLot == "" && strLot_Text != "")
                    {
                        int lotid = 0;
                        strSql = string.Format(@"select t1.FLOTID from T_BD_LOTMASTER t1 where t1.FNUMBER='{0}' and t1.FMATERIALID='{1}' and t1.FUSEORGID='{2}' and t1.FBIZTYPE=1  ", strLot_Text, strMaterial, strFSTOCKORG);
                        using (IDataReader dr = DBUtils.ExecuteReader(this.Context, strSql))
                        {
                            while (dr.Read())
                            {
                                lotid = Convert.ToInt32(dr["FLOTID"]);
                            }
                            dr.Close();
                        }

                        strSql = string.Format(@"select t.FID,t.F_ST_QTY,t.F_ST_COUNTQTY,t.F_ST_PAIRQTY,
                                                    t.F_ST_PURORDERBILLNO,t.F_ST_SALEORDERBILLNO,
                                                    t.F_ST_SPROWNO,t.F_ST_ORIGINALBATCH,t.F_ST_SUPPLYID
                                                    from [st_T_STK_INVENTORY_EXP] t 
                                                    where t.fid in (select t1.fid from [T_STK_INVENTORY] t1 
                                                                    where t1.FOWNERTYPEID='{0}' and t1.FOWNERID='{1}' and t1.FKEEPERTYPEID='{2}' 
                                                                    and t1.FKEEPERID='{3}' and t1.FSTOCKORGID='{4}'
                                                                    and t1.FSTOCKID='{5}' and t1.FSTOCKLOCID='{6}'
                                                                    and t1.FAUXPROPID='{7}' and t1.FSTOCKSTATUSID='{8}' and t1.FLOT='{9}'
                                                                    and t1.FBOMID='{10}' and t1.FMTONO='{11}'
                                                                    and t1.FPROJECTNO='{12}' and {13}
                                                                    and {14} and t1.FMATERIALID='{15}')",
                                                                        strOwnerType, strOwner,
                                                                        strKeeperType, strKeeper, strFSTOCKORG,
                                                                        strStock, currRow["StockLocID"],
                                                                        strAuxProp, strStockStatus,
                                                                        lotid, currRow["BomID"],
                                                                        currRow["MTONO"], currRow["ProjectNo"],
                                                                        strProduceDate, strExpiryDate,
                                                                        strMaterial);
                        dt = DBUtils.ExecuteDataSet(this.Context, strSql).Tables[0];
                    }
                    else
                    {
                        strSql = string.Format(@"select t.FID,t.F_ST_QTY,t.F_ST_COUNTQTY,t.F_ST_PAIRQTY,
                                                    t.F_ST_PURORDERBILLNO,t.F_ST_SALEORDERBILLNO,
                                                    t.F_ST_SPROWNO,t.F_ST_ORIGINALBATCH,t.F_ST_SUPPLYID
                                                    from [st_T_STK_INVENTORY_EXP] t 
                                                    where t.fid in (select t1.fid from [T_STK_INVENTORY] t1 
                                                                    where t1.FOWNERTYPEID='{0}' and t1.FOWNERID='{1}' and t1.FKEEPERTYPEID='{2}' 
                                                                    and t1.FKEEPERID='{3}' and t1.FSTOCKORGID='{4}'
                                                                    and t1.FSTOCKID='{5}' and t1.FSTOCKLOCID='{6}'
                                                                    and t1.FAUXPROPID='{7}' and t1.FSTOCKSTATUSID='{8}' and t1.FLOT='{9}'
                                                                    and t1.FBOMID='{10}' and t1.FMTONO='{11}'
                                                                    and t1.FPROJECTNO='{12}' and {13}
                                                                    and {14} and t1.FMATERIALID='{15}')",
                                                                            strOwnerType, strOwner,
                                                                            strKeeperType, strKeeper, strFSTOCKORG,
                                                                            strStock, currRow["StockLocID"],
                                                                            strAuxProp, strStockStatus,
                                                                            strLot, currRow["BomID"],
                                                                            currRow["MTONO"], currRow["ProjectNo"],
                                                                            strProduceDate, strExpiryDate,
                                                                            strMaterial);
                        dt = DBUtils.ExecuteDataSet(this.Context, strSql).Tables[0];
                    }
                    if (dt.Rows.Count != 0)
                    {
                        #region 将[st_T_STK_INVENTORY_EXP]表中扩展字段值插入当前操作行中

                        //库存单据默认长度单位为米，非库存单据默认长度单位为组 
                        this.View.Model.SetValue("F_st_UnitID", dt.Rows[0]["F_ST_QTY"], i);
                        //长度，只数，双数
                        this.View.Model.SetValue("F_st_Qty", dt.Rows[0]["F_ST_QTY"], i);
                        this.View.Model.SetValue("F_st_CountQty", dt.Rows[0]["F_ST_COUNTQTY"], i);
                        this.View.Model.SetValue("F_st_PairQty", dt.Rows[0]["F_ST_PAIRQTY"], i);
                        //购销单号、、、、
                        this.View.Model.SetValue("F_st_PurOrderBillNo", dt.Rows[0]["F_ST_PURORDERBILLNO"], i);
                        this.View.Model.SetValue("F_st_SaleOrderBillNo", dt.Rows[0]["F_ST_SALEORDERBILLNO"], i);
                        this.View.Model.SetValue("F_st_SPRowNo", dt.Rows[0]["F_ST_SPROWNO"], i);
                        this.View.Model.SetValue("F_st_OriginalBatch", dt.Rows[0]["F_ST_ORIGINALBATCH"], i);
                        this.View.Model.SetValue("F_st_SupplyID", dt.Rows[0]["F_ST_SUPPLYID"], i);

                        //更新单据
                        this.View.UpdateView(Entity.Key);

                        #endregion

                        strSql = string.Format("select * from st_T_STK_INVENTORY_EXPENTRY t where t.FID='{0}' order by t.F_ST_SIZE", dt.Rows[0]["FID"]);
                        DataTable dtExp = DBUtils.ExecuteDataSet(this.Context, strSql).Tables[0];

                        #region 将[st_T_STK_INVENTORY_EXPENTRY]表中的双数明细插入当前单据的子单据双数明细中

                        //删除双数明细的全部行
                        Entity fSubEntity = this.View.BillBusinessInfo.GetEntity("FSubEntity");
                        DynamicObjectCollection subEntityRows = this.View.Model.GetEntityDataObject(fSubEntity);
                        subEntityRows.Clear();

                        int rownum = 0;
                        foreach (DataRow dr in dtExp.Rows)
                        {
                            View.Model.CreateNewEntryRow("FSubEntity");
                            this.View.Model.SetValue("F_st_LR", dr["F_ST_LR"], rownum);
                            this.View.Model.SetValue("F_st_COLOR", dr["F_ST_COLOR"], rownum);
                            this.View.Model.SetValue("F_st_SIZE", dr["F_ST_SIZE"], rownum);
                            this.View.Model.SetValue("F_st_PAIRDETAILQTY", dr["F_ST_PAIRDETAILQTY"], rownum);
                            rownum++;
                        }
                        this.View.UpdateView("FSubEntity");
                        this.View.Model.SetValue("F_st_Text", "");
                        this.View.UpdateView("F_st_Text");

                        #endregion
                    }
                }
            }

        }

        #region
        /// <summary>
        /// 操作完成后触发
        /// </summary>
        /// <param name="e"></param>
        public override void AfterDoAction(AfterDoActionEventArgs e)
        {
            base.AfterDoAction(e);

            //作废单据等操作影响库存的实现代码区
        }


        /// <summary>
        /// 库存更新方法
        /// 需要设置参数：货主、货主保管者、库存组织、仓库、仓位、批号、物料
        /// </summary>
        public void ChangeInventory()
        {

        }

        #endregion
    }
}
